<template>
  <div class="content doc_content">
    <el-dialog
      title="上传文件"
      :visible.sync="fileVisible"
      width="65%"
      :before-close="addClose" :show-close="false" :close-on-click-modal="true"
      :close-on-press-escape="true">
      <file-upload-input ref="fileUploader" :fileFilter="fileCreateFilterList"></file-upload-input>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addClose('fileVisible')">取 消</el-button>
          <el-button type="primary"
                     @click="()=>{ this.submitAdd('fileVisible').then(()=>{this.reloadDisk();this.fileVisible = false})}">
            上传
          </el-button>
        </span>
    </el-dialog>
    <el-dialog
      title="预览文件"
      :visible.sync="preViewShow"
      width="70%"
      :before-close="()=>{this.preViewShow=false;}" :show-close="true" :close-on-click-modal="false"
      :close-on-press-escape="true"
      ref="documentPreviewDialog">
      <document-preview :previewInfo.sync="preViewInfo" style="width: 100%;height: 50rem"
                        ref="documentPreview"></document-preview>
    </el-dialog>
    <remind-input :remind-form-show="showRemindInput" @done="closeRemind"></remind-input>
    <el-container style="height: 100%">
      <el-row :gutter="2" style="width: 100%;height: 100%">
        <el-col v-show="showCompanyList" :span="5" style="height: 100%;width:348px;">
          <company-selector ref="companySelector" :init-datas.sync="companyList"
                            @companySelect="companyChange" @companySearch="searchCompany"></company-selector>
        </el-col>
        <el-col :span="fileContainerWidth" :style="{height: '100%',width: showCompanyList?'calc(100% - 348px)':'100%'}">
          <div v-if="!diskInfo" style="width: 80%;height: auto;position:absolute;">
            没有获取到磁盘信息,无法对档案进行操作
          </div>
          <div>
          <file-container v-show="diskInfo" ref="fileContainer" :init-datas.sync="fileListData"
                          @remindSet="setRemind"
                          @preViewFile="preViewFile"
                          :rootPath.sync="startPath"
                          :company="showCompanyList"
                          :apiFileList.sync="apis.fileListApi"
                          :apiDeskInfo.sync="apis.diskInfoApi"
                          :api-file-del.sync="apis.apiFileDel"
                          :disk-info.sync="diskInfo"
                          @fileSelected="selectedFile"
                          into-file-type="FOLDER"
                          root="DISK"
                          :fileCtrl="fileCtrl"
                          @newFile="openNewFile" :file-types="[]" ></file-container>
          </div>
        </el-col>
      </el-row>
      <el-dialog
        title="创建文件夹"
        :visible.sync="folderVisible"
        width="30%"
        :before-close="addClose" :show-close="false" :close-on-click-modal="true"
        :close-on-press-escape="true">
        <folder-input ref="folderInput" @valueOk="folderValueOk"></folder-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addClose('folderVisible')">取 消</el-button>
          <el-button type="primary"
                     @click="()=>{ this.submitAdd('folderVisible').then(()=>{this.folderVisible = false})}"
                     v-bind:disabled="folderAddDisable">确 定</el-button>
        </span>
      </el-dialog>
    </el-container>
  </div>
</template>
<script>
import CompanySelector from "../../components/common/CompanySelector"
import FileContainer from "../../components/common/FileContainer";
import FolderInput from "./FolderInput";
import Api from "../../support/Api";
import RemindInput from "@/components/common/RemindInput";
import FileUploadInput from "@/components/common/FileUploadInput";
import DocumentPreview from "@/components/common/DocumentPreview";

export default {
  components: {
    FileUploadInput,
    CompanySelector,
    FileContainer,
    FolderInput,
    RemindInput,
    DocumentPreview
  },
  beforeRouteEnter(to, from, next) {
    if (to.fullPath.indexOf('company') > -1) {
      next(vm => {
        vm.doCompanyShow(to.query)
      });
      return;
    }
    next(vm => {
      vm.doZoneShow(to.query);
    });
  },
  data() {
    return {
      preViewInfo: null,
      companyList: [],
      showUploadFile: false,
      fileListData: {dataList: [], total: 0},
      diskInfo: {
        space: 0,
        spaceFree: 0
      },
      fileContainerWidth: 19,
      showCompanyList: true,
      files: [],
      folderAddDisable: true,
      fileAddDisable: true,
      fileVisible: false,
      folderVisible: false,
      fileCreateFilterList: [],
      fileCtrl: {
        fileVisible: {
          type: 0,
          input: "newFileValue",
          submit: "fileAddDisable",
          el: "fileUploader",
          ctrlName: '新建文件'
        },
        folderVisible: {
          type: 'FOLDER',
          input: "newFolderValue",
          submit: "folderAddDisable",
          el: "folderInput",
          ctrlName: '新建文件夹'
        }
      },
      apis: {
        fileListApi: null,
        diskInfoApi: null,
        apiFileDel: null
      },
      showRemindInput: false,
      selectedFileData: [],
      companyId: 1,
      preViewShow: false,
      companyName: '',
      startPath: null
    };
  },
  created() {
    let self = this;
    this.apiInvoker = Api.newInstance(this, 1, 'cloudFile');
    this.apis = {
      fileListApi: this.apiInvoker.invoker('fileList'),
      diskInfoApi: this.apiInvoker.invoker('diskInfo'),
      companyListApi: this.apiInvoker.invoker('companyList'),
      ossSig: this.apiInvoker.invoker('ossSig').execute(data => {
        self.uploadSig = data.data;
      }, 'get'),
      apiFileDel: this.apiInvoker.invoker('deleteFile')
    }
  },
  mounted() {

  }
  ,
  methods: {
    searchCompany(name) {
      let self = this;
      this.companyList.splice(0, this.companyList.length);
      this.apis.companyListApi.execute(data => {
        let df = self.setCompanyData(data.data.records);
        self.apis.diskInfoApi.execute(diskInfo => {
          self.setDiskInfo(diskInfo, self.startPath)
        }, 'get', {
          relationId: df
        })
      }, 'get', (!name || name === '') ? {relationId: 0} : {
        name: name
      });
    },
    doZoneShow(startPath) {
      let self = this;
      this.startPath = startPath;
      this.fileContainerWidth = 24;
      this.showCompanyList = false;
      this.companyList = [];
      this.apis.diskInfoApi.execute(diskInfo => {
        self.setDiskInfo(diskInfo, startPath)
      }, 'get', {})
    },
    doCompanyShow(startPath) {
      this.fileContainerWidth = 19;
      this.showCompanyList = true;
      this.startPath = startPath;
      let self = this;
      this.apis.companyListApi.execute(data => {
        self.apis.diskInfoApi.execute(diskInfo => {
          self.setDiskInfo(diskInfo, startPath)
        }, 'get', {
          relationId: self.setCompanyData(data.data.records)
        })
      }, 'get')
    },
    preViewFile(row) {
      this.preViewShow = true;
      this.preViewInfo = row;
      // this.$ge.$emit('preview-document-reload',true);
    }
    ,
    setCompanyData(dataList) {
      let defaultId = 0;
      this.companyList = [];
      for (let c in dataList) {
        let obj = dataList[c];
        obj.act = (c * 1 === 0);
        if (obj.act) this.companyName = obj.name;
        defaultId = (c * 1 === 0) ? obj.id : defaultId;
        this.companyList.push(obj);
      }
      this.$refs.companySelector.checkCompanyList(this.companyList);
      return defaultId;
    },
    setDiskInfo(data, startPath) {
      this.diskInfo = data.data;
      if (!data || !data.data) {
        return;
      }
      this.diskInfo.modify = false;
      if (data.data) {
        if (startPath) {
          startPath.type = 'DISK';
          startPath.value = this.diskInfo.id;
        }
        this.$refs.fileContainer.loadData(startPath ? startPath : {
          value: this.diskInfo.id,
          type: 'DISK'
        }, this.fileListApi);
      }
    }
    ,
    reloadDisk() {
      let self = this;
      this.apis.diskInfoApi.execute(data => {
        self.diskInfo = data.data;
        self.diskInfo.modify = true;
      }, 'get', {
        relationId: self.companyId
      });
    },
    companyChange(selectedCompany) {
      this.companyId = selectedCompany.id;
      this.companyName = selectedCompany.name;
      let self = this;
      this.apis.diskInfoApi.execute(diskInfo => {
        self.setDiskInfo(diskInfo, self.startPath)
      }, 'get', {
        relationId: selectedCompany.id
      });
    }
    ,
    closeRemind(data) {
      let self = this, submitList = [], dirs = this.$refs.fileContainer.getDeepList().join("/");
      if (self.selectedFileData.length > 0) {
        for (let file of this.selectedFileData) {
          submitList.push({
            name: "(" + file.name + ")文件到期提醒",
            bizType: 'FILE_REMIND',
            expression: data.expression,
            preDays: data.preDays,
            delayUnit: 'DAYS',
            desPrefix: "<span class='no_filePath'>" + self.companyName + "</span>" + (self.showCompanyList ? '企业' : '园区') + "的<span class='no_filePath'>" + dirs + "/" + file.name + "</span>文件，",
            relationId: file.id
          });
        }
        if (data) {
          this.apiInvoker.invoker('addReminds', submitList, false).executeArray(data => {
            self.$refs.fileContainer.loadData();
          }, 'post')
        }
      }
      this.showRemindInput = false;
    }
    ,
    openNewFile(info) {
      this[info.type] = true;
      this.parentInfo = info.data;
    }
    ,
    selectedFile(data) {
      this.selectedFileData = data;
    }
    ,
    setRemind() {
      this.showRemindInput = true;
    }
    ,
    submitAdd(type) {
      let self = this;
      if (type === 'fileVisible') {
        let fileList = this.$refs.fileUploader.getPreFiles();
        let taskList = [];
        for (const index in fileList) {
          if (Object.hasOwnProperty.call(fileList, index)) {
            let item = fileList[index], name = item.name || item.nativeName,
              keyValue = 'ep/web/' + this.uuid() + "::" + name + (item.type ? ("." + item.type) : ''),
              ossData = new FormData()//创建oss数据对象
            ossData.append('name', name + (item.type ? ("." + item.type) : ''))
            ossData.append('key', keyValue)
            ossData.append('policy', self.uploadSig.policy)
            ossData.append('OSSAccessKeyId', self.uploadSig.accessId)
            ossData.append('success_action_status', 200)
            ossData.append('Signature', self.uploadSig.signature)
            ossData.append('file', item.raw)
            taskList.push({
              name: 'ossUpload',
              method: 'post',
              param: ossData,
              fileName: name,
              type: item.type,
              path: "https://huancehuanbao.oss-cn-hangzhou.aliyuncs.com/" + keyValue,
              size: item.raw.size
            });
          }
        }
        return {
          then(cb) {
            self.apiInvoker.invokerList(taskList).execute((data, index, done) => {
            }).then(dataList => {
              self.apiInvoker.invoker('addFiles', ((p) => {
                let postParams = [];
                for (let index in p) {
                  postParams.push({
                    path: taskList[index].path,
                    name: taskList[index].fileName,
                    type: taskList[index].type,
                    fileType: 'FILE',
                    parent: self.parentInfo.value,
                    size: taskList[index].size,
                    parentType: self.parentInfo.type
                  });
                }
                return postParams;
              })(dataList), false).executeArray(resp => {
                if (resp.data) {
                  self.$refs.fileContainer.loadData();
                  self.$refs[self.fileCtrl[type].el].clear();
                  cb();
                }
                // self.$refs[self.fileCtrl[type].el].exitsShow(resp.msg);
              });
            });
            cb();
          }
        }
      }
      return {
        then(cb) {
          self.apiInvoker.invoker('addFile', {
            name: self[self.fileCtrl[type].input],
            fileType: self.fileCtrl[type].type ? self.fileCtrl[type].type : 'file',
            parent: self.parentInfo.value,
            size: 0,
            parentType: self.parentInfo.type
          }, true).execute(resp => {
            if (resp.data) {
              self.$refs.fileContainer.loadData();
              self.$refs[self.fileCtrl[type].el].clear();
              cb();
              return;
            }
            self.$refs[self.fileCtrl[type].el].exitsShow(resp.msg);
          });
        }
      };
    }
    ,
    addClose(type) {
      if (typeof type !== 'string') {
        return;
      }
      this[type] = false;
      this.$refs[this.fileCtrl[type].el].clear();
      try {
        this.$refs[this.fileCtrl[type].el].exitsShow(0);
      } catch (e) {
      }
    }
    ,
    folderValueOk(value) {
      this[this.fileCtrl.folderVisible.submit] = !value.status;
      this[this.fileCtrl.folderVisible.input] = value.value.name;
    }
  },
  watch: {
    showCompanyList: {
      handler(n, o) {
      }
    }
  }
}
;
</script>
<style>
::-webkit-scrollbar {
  width: 5px; /* 纵向滚动条*/
  height: 5px; /* 横向滚动条 */
  background-color: #fff;
}

/*定义滚动条轨道 内阴影*/
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0);
  background-color: #ccc;
}

/*定义滑块 内阴影*/
::-webkit-scrollbar-thumb {
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0);
  background-color: #1890ff;
  border-radius: 10px;
}

.el-date-picker > .el-picker-panel__footer > .el-button--text {
  /*display: none;*/
  visibility: hidden;
}

.doc_content {
  height: 85vh;
}

.no_filePath {
  font-weight: bold;
  color: #409EFF;
  letter-spacing: 1px;
}
</style>
